package com.mapperdb.scripting.xmltags;

import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.scripting.xmltags.DynamicContext;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.scripting.xmltags.StaticTextSqlNode;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.UnknownTypeHandler;

public class AttrSqlNode implements SqlNode {
	protected Result result;
	protected String property;

	public AttrSqlNode(Result result) {
		this.result = result;
		this.property = result.property();
	}

	public AttrSqlNode(Result result, String property) {
		this.result = result;
		this.property = property;
	}

	@Override
	public boolean apply(DynamicContext context) {
		String text = format();
		newSqlNode(text).apply(context);
		return true;
	}

	protected static SqlNode newSqlNode(String text) {
		return new StaticTextSqlNode(text);
	}

	protected String format() {
		Class<?> javaType = result.javaType();
		JdbcType jdbcType = result.jdbcType();
		Class<? extends TypeHandler<?>> typeHandler = result.typeHandler();

		StringBuffer sb = new StringBuffer();
		sb.append("#{").append(property);
		if (javaType != null && javaType != Void.TYPE) sb.append(",javaType=").append(javaType.getName());
		if (jdbcType != null && jdbcType != JdbcType.UNDEFINED) sb.append(",jdbcType=").append(jdbcType.name());
		if (typeHandler != null && typeHandler != UnknownTypeHandler.class)
			sb.append(",typeHandler=").append(typeHandler.getName());
		sb.append("}");
		return sb.toString();
	}
}
